/**
 * @Name: 图片点字验证码插件
 * @Revison: 1.0
 * @Date: 22/12/2017
 * @Author: Atticus
 * @Support: jquery
 * @Use: $.imageCode(options);
 */
;
(function($, window, document, undefined) {
	var ImageCode = function(ele, opts) {
		this.$element = ele;
		
		this.defaults = {
			flag: true,				// 是否使用默认配置
			imageWidth: 280,		// 生成图片的宽度
			imageHeight: 200,		// 生成图片的高度
			imageCodeHeight: 160,	// 供点击图片的高度
			sourceCodeWidth: 100,	// 参考图片宽度
			fontWidth: 30,			// 供点击图片文字字体大小
			sourceFontWidth: 20,	// 参考图片文字字体大小
			degree: 30,				// 旋转角度
			style: {				// 自定义样式

			},
			callback: function() {	// 验证成功
				
			}
		};
		
		this.opts = $.extend({}, this.defaults, opts || {});
	};
	
	ImageCode.prototype = {
		containerID: 'IC_container',
		
		codeURL: 'ecp/imageCode',
		
		vfyURL: 'ecp/security',
		
		oArr: ['imageHeight', 'imageWidth', 'imageCodeHeight', 'sourceCodeWidth', 'fontWidth', 'sourceFontWidth', 'degree', 'flag'],
		
		imgURL: '',
		
		clickData: [],
		
		tips: {
			M1: '请顺序点击大图中的文字',
			M2: '请选择图中文字进行验证',
			M3: '再次点击图标可取消并重选',
			M4: '验证错误，请重新验证'
		},
		
		init: function() {
			var _this = this;
			return this.$element.each(function() {
				$('body').append(_this.rendView());
				
				_this.setPosition($(this));
				
				_this.bindEvent($(this));
			});
		},
		
		rendView: function() {
			this._setImgURL();
			
			$('#' + this.containerID).remove();
			
			var s = '<div class="ic_container" id="'+ this.containerID +'">' +
        			'<div class="ic_area">' +
            			'<div class="ic_layout">' +
            				'<div class="ic_guide clearfix">' +
            					'<span class="ic_info">'+ this.tips.M1 +'</span>' +
            					'<div class="ic_standard">' +
            						'<img src="'+ this.imgURL +'">' +
            					'</div>' +
            				'</div>' +
            				'<div class="ic_oripic">' +
            					'<img src="'+ this.imgURL +'" data-iclick="bimg">' +
            				'</div>' +
            			'</div>' +
            			'<div class="ic_oparea clearfix">' +
            				'<div class="ic_refresh" data-iclick="refresh">' +
            					'<a class="aq_icon aq_icon_refresh" href="javascript:;" title="换一张图片"></a>' +
            				'</div>' +
            				'<span class="ic_btn ic_btn_primary" data-iclick="submit">验证</span>' +
            			'</div>' +
            		'</div>' +
                		'<div class="ic_tip_success">' +
    					'<div class="ic_tip_bkg"></div>' +
    					'<div class="ic_tip_icon">' +
    						'<div class="ic_pic"><i></i></div>' +
    						'<p class="ic_vfyword">验证成功</p>' +
    					'</div>' +
    				'</div>' +
				'</div>';
			
			return s;
		},
		
		setPosition: function($ele) {
			var top = $ele.offset().top - this.opts.imageHeight / 2 - $ele.outerHeight() / 2 - 5,
				left = $ele.offset().left + $ele.outerWidth() / 3;
			
			$('#' + this.containerID).css($.extend({
				width: this.opts.imageWidth + 9 * 2,
				height: this.opts.imageHeight + 77,
				left: left,
				top: top
			}, this.opts.style || {})).addClass('show');
		},
		
		bindEvent: function($ele) {
			var _this = this;
			
			$('body').on('click', function() {
				var $container = $('#' + _this.containerID);
				
				$container.removeClass('show');
				setTimeout(function() {
					$container.remove();
				}, 300);
			});
			
			 $('#' + this.containerID).on('click', function(e) {
				 e.stopPropagation();
			});
			
			 $('#' + this.containerID).on('click', '*[data-iclick]', function(e) {
				e.stopPropagation();
				var ic = $(this).attr('data-iclick');
				
				switch(ic) {
					case 'refresh': // 刷新
						_this._refreshImg();
						break;
					case 'bimg': 
						_this._clickImg(e);
						break;
					case 'select': 
						_this._removeICSelect($(this));
						break;
					case 'submit': // 验证
						_this._verifyImg();
						break;
					default: 
						break;
				};
			});
		},
		
		// 设置图片路径
		_setImgURL: function() {
			var tmpArr = [];
			
			for (var i = 0, l = this.oArr.length; i < l; i++) {
				var d = this.oArr[i];
				
				if (this.opts[d]) {
					tmpArr.push(d + '=' + this.opts[d]);
				}
			}
			
			this.imgURL = this.codeURL + '?' + tmpArr.join('&') + '&rand=' + new Date().getTime();
		},
		
		// 刷新验证码图片
		_refreshImg: function(tipsFlag) {
			var $container = $('#' + this.containerID),
				$select = $('.ic_oripic .ic_select', $container);
			
			// 设置图片地址
			this._setImgURL();
			$('img', $container).attr('src', this.imgURL);
			
			// 移除点击数据
			$select.remove();
			this.clickData = [];
			
			if (tipsFlag != false) {
				// 重新设置提示
				this._setTipsMsg(1);
			}
		},
		
		// 点击图片
		_clickImg: function(e) {
			var $container = $('#' + this.containerID),
				$oripic = $('.ic_oripic', $container),
				$select = $('.ic_oripic .ic_select', $container),
				left = e.offsetX,
				top = e.offsetY,
				index = $select.length + 1;
			
			if (index < 5 && left >= 10 && left <= this.opts.imageWidth - 10 && top >= 10 && top <= this.opts.imageCodeHeight - 10) {
				this._setTipsMsg(3);
				
				var s = '<div class="ic_select" data-iclick="select" style="left: '+ (left - 10) +'px; top: '+ (top - 10) +'px;"><div class="aq_icon aq_icon_shield_click"></div>'+ index +'</div>';
				
				this.clickData.push({
					left: left,
					top: top
				});
				
				$oripic.append(s);
			}
		},
		
		// 移除选中
		_removeICSelect: function($ele) {
			var $container = $('#' + this.containerID),
				index = $('.ic_oripic .ic_select', $container).index($ele);
			
			$ele.nextAll('.ic_select').remove().end().remove();
			
			this.clickData.splice(index);
			
			var $select = $('.ic_oripic .ic_select', $container);
			if ($select.length === 0) {
				this._setTipsMsg(1);
			}
		},
		
		// 验证图片
		_verifyImg: function() {
			var $container = $('#' + this.containerID),
				$select = $('.ic_oripic .ic_select', $container),
				$tips = $('.ic_info', $container),
				_this = this;
			
			if ($select.length === 0) {
				this._shake();
				this._setTipsMsg(2);
			} else {
				// 获取点击数据
				var dataArr = [];
				for(var i = 0, l = this.clickData.length; i < l; i++) {
					var d = this.clickData[i];

					dataArr.push(d.left);
					dataArr.push(d.top);
				}
				
				$.post(this.vfyURL, {
					vcode: dataArr.join(',')
				}, function(data) {
					data = $.parseJSON(data);
					
					if (data && data.result) {
						var $container = $('#' + _this.containerID);
						
						$('.ic_tip_success', $container).show();
						setTimeout(function () {
                            $container.removeClass('show');
                        },1500)
						_this.opts.callback.call(null, data);
					} else {
						_this._shake();
						_this._setTipsMsg(4);
						_this._refreshImg(false);
					}
				}, 'text');
			}
		},
		
		_shake: function() {
			var $container = $('#' + this.containerID);
			
			$container.addClass('shake');
			
			setTimeout(function() {
				$container.removeClass('shake')
			}, 300);
		},
		
		// 设置提示
		_setTipsMsg: function(type) {
			var $container = $('#' + this.containerID),
				$select = $('.ic_oripic .ic_select', $container),
				$tips = $('.ic_info', $container);
			
			switch(type) {
				case 1:
					$tips.html(this.tips.M1).css('color', '#666');
					break;
				case 2:
					$tips.html(this.tips.M2).css('color', '#ff8a00');
					break;
				case 3:
					$tips.html(this.tips.M3).css('color', '#666');
					break;
				case 4:
					$tips.html(this.tips.M4).css('color', '#ff8a00');
					break;
				default: 
					break;
			}
		}
	}
	
	$.fn.imageCode = function(options) {
		// 创建ImageCode的实例
		var code = new ImageCode(this, options);
		
		setTimeout(function() {
			// 调用方法
			code.init();
		}, 0);
		
		return code;
	}
})(jQuery, window, document);
